package com.fit.pages.user;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.fit.annotations.AdminAccess;
import com.fit.annotations.ProfessorAccess;
import com.fit.annotations.StudentAccess;
import com.fit.components.Layout;
import com.fit.dao.user.UserDAO;
import com.fit.entities.user.User;
import com.fit.model.MD5;
import com.fit.pages.ErrorPage;
import com.fit.pages.Index;
import com.fit.services.Authenticator;

@AdminAccess
@ProfessorAccess
@StudentAccess
public class ChangePassword {
	
//	@Inject
//	private Session session;
	

	@Property
	private User user;
	
	@Property
	private String newPassword;
	

	@Property
	private String newPassword2;
	
	@Inject
	private UserDAO userDAO;
	
	public User getLoggedUser() {
//		if (authenticator.isLoggedIn()) {
			return authenticator.getLoggedUser();
//		}
//		return null;
	}	

	@Inject
	private Authenticator authenticator;

	
	@InjectPage
	private ErrorPage errorPage;
	
	@Component
	private Form changeForm;
	
	Object onSuccessFromChangeForm() {
		System.out.println("kako jeee"+getLoggedUser().getId());
		user = userDAO.findByID(getLoggedUser().getId());
		try {
			if (newPassword != null) {
				System.out.println("1");
				if(newPassword.equalsIgnoreCase(newPassword2)){
					System.out.println("2");
					newPassword = MD5.md5(newPassword);
					user.setPassword(newPassword);
					System.out.println("3");
					System.out.println(newPassword + newPassword2);
					getLoggedUser().setPassword(newPassword);
					userDAO.update(user);
					
					System.out.println("PASSWORD POSLE UPDATEA" + getLoggedUser().getPassword());
					return Index.class;
					
//				if (newPassword.equals(user.getPassword())) {
//						System.out.println("4");
//						user.setPassword(newPassword);
//						System.out.println("5");
//					}
				}
				
			}
			System.out.println("4");
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			errorPage.setMessage("Error! ");
			return errorPage;
		}

	}
	
	

}
